package com.xiaoxie.cloud.controller;

import com.xiaoxie.cloud.entities.PayDTO;
import com.xiaoxie.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
public class OrderController {

    // 支付微服务地址，这里硬编码写死
    // private static final String PAYMENT_URL = "http://localhost:8001";
    // 使用在注册中心注册的微服务名称，这里是cloud-payment-service，端口号也不用写了
    private static final String PAYMENT_URL = "http://cloud-payment-service";

    private final RestTemplate restTemplate;

    // 创建支付订单
    @PostMapping("/consumer/pay/add")
    public ResultData addOrder(@RequestBody PayDTO payDTO) {
        return restTemplate.postForObject(PAYMENT_URL + "/pay/add", payDTO, ResultData.class);
    }

    // 查询支付订单
    @GetMapping("/consumer/pay/get/{id}")
    public ResultData getOrder(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(PAYMENT_URL + "/pay/get/" + id, ResultData.class);
    }

    // 删除支付订单
    @DeleteMapping("/consumer/pay/del/{id}")
    public ResultData delOrder(@PathVariable("id") Integer id) {
        restTemplate.delete(PAYMENT_URL + "/pay/del/" + id);
        return ResultData.success("删除成功");
    }

    // 修改支付订单
    @PutMapping("/consumer/pay/update")
    public ResultData updateOrder(@RequestBody PayDTO payDTO) {
        restTemplate.put(PAYMENT_URL + "/pay/update", payDTO);
        return ResultData.success("修改成功");
    }

    @GetMapping("/consumer/pay/get/info")
    private String getInfoByConsul() {
        return restTemplate.getForObject(PAYMENT_URL + "/pay/get/info", String.class);
    }

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/discovery")
    public String discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info(service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return instances.get(0).getServiceId() + ":" + instances.get(0).getPort();
    }
}
